package org.example.SlApi.JbxxApi;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.apache.commons.codec.net.URLCodec;
import org.example.JycInfo;
import org.example.utils.ConPlsqla;
import org.example.utils.ReadConf;
import org.example.utils.TestDataLoader;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.example.RestClient.givenWithCookies;
import static org.example.RestClient.loginAndUpdateCookies;

public class ZsbcApi {

    private  static TestDataLoader testDataLoader;
    private static List<JycInfo> JycList = new ArrayList<>();
    public static void main(String[] args) throws SQLException, UnsupportedEncodingException, ClassNotFoundException, IOException {
        // 直接在 main 方法中初始化 testDataLoader
        testDataLoader = new TestDataLoader();
        zsbcApi();
    }

    public static int zsbcApi() throws IOException {//住所二次保存

        if (testDataLoader == null) {
            testDataLoader = new TestDataLoader();
        }
        // 登录并更新cookies
        loginAndUpdateCookies();


        List<JycInfo> jycInfoList = initJyclist(); // 调用方法来获取列表
        if (!jycInfoList.isEmpty()) {
            JycInfo firstJycInfo = jycInfoList.get(0); // 获取列表中的第一个元素
            String nameid = firstJycInfo.getName_id(); // 使用实际的getter方法
            String sbid = firstJycInfo.getSbid();
            String pripid = firstJycInfo.getPripid();
            String entname = firstJycInfo.getEntname();
            String proloc_location = firstJycInfo.getProloc_location();//详细地址
//            String proloc = firstJycInfo.getProloc();//地址
            String qylxdl = firstJycInfo.getQylxdl();//地址

            Map<String, String> testData = testDataLoader.getTestData();
            String S_PROLOC = testData.get("S_PROLOC");
            String S_DOM_LOCATION = testData.get("S_DOM_LOCATION");
            String proloc = S_PROLOC + S_DOM_LOCATION;//地址

            URLCodec urlCodec = new URLCodec();
            String encodedParam = URLEncoder.encode(entname, "UTF-8");
            String encodedParam2 = URLEncoder.encode(proloc_location, "UTF-8");
            String encodedParam3 = URLEncoder.encode(proloc, "UTF-8");

            RestAssured.baseURI = ReadConf.getHost(); // 设置基础URI
            String data = "method=edit&sbid="+sbid+"&pripid="+pripid+"&entname="+encodedParam+"&entid="+nameid+"&enttype=1200&regno=&regorg=330102&qylxdl="+qylxdl+"&sbms=1&ljmsign=2&znspsign=0&bdcsign=&name_id="+nameid +"&S_ITE=0&S_ITENAME=&S_ITEREGNO=&jbxx=S_REGCAP_%3A1000_%2CS_IS_QCTB_%3A0_%2CS_SHDJJG_%3A_%2CS_REGORG_%3A330100_%2CS_LOCALADM_%3A33010203_%2CS_ENTNAME_%3A"+encodedParam+"_%2CS_JYQX_%3A999_%2CS_QYLXDL_%3A"+qylxdl+"_%2CS_INDUSTRYPHY_%3A7484_%2CS_TEL_%3A_%2CS_NAME_ID_%3A"+nameid+"_%2CS_INSFORM_%3A_%2CN_EMPNUM_%3A_%2CS_OPSCOPE_%3A_%2CS_DOMPRORIGHT_%3A1&qyzc=S_JSRS_%3A3_%2CS_JSRS_ZGDB_%3A1_%2CS_DSRS_%3A3_%2CS_FDSZRS_%3A0_%2CS_DSRS_ZGDB_%3A0_%2CS_JLJRQK_%3A0_%2CS_PRIPID_%3A"+pripid+"_%2CS_ZCMB_%3A1106&zyryxgbz=&FZXX=&label=&S_NAME_ID="+nameid+"&S_ENTNAME="+encodedParam+"&S_DOM_PROVINCE=330000&S_DOM_CITY=330100&S_DOM_DISTRICT=330102&S_DOM_STREET=330102001&S_DOM_LOCATION="+encodedParam2+"&S_DOMPRORIGHT=1&S_INDUSTRYPHY=7484&addrContent=&addrCode=&IS_QCTB=0&S_SHDJJG=&S_LOCALADM=33010203&S_DOM="+encodedParam3+"&N_EMPNUM=&S_TEL=&S_REGCAP=1000&S_ENTTYPE=&SFCQ=1&S_ZZFBS=&S_CNO=&S_JYFWPXSIGN=0&S_ISYZDZ=0&S_YZDZ=&S_CERTSEPREGIST=1&S_OPSCOPE=&mainTypeOne=&mainTypeTwo=&mainTypeTre=&chooseopscope=&isrestrict=&jyfw_xkxm=&jyfw_ybxm=&opscope_xkxm=&opscope_ybxm=&opscope_xkxm_isrestrict=&opscope_ybxm_isrestrict=&S_OPSCOPE_HAND=&haveNoPreapprovalitems=&YRGF=0&JS=1&S_JSRS=&S_JSRS_ZGDB=&S_DSRS=&S_FDSZRS=&S_DSRS_ZGDB=&S_JSRS=&S_JSRS_ZGDB=&S_DSRS=3&S_FDSZRS=0&S_DSRS_ZGDB=0&S_JSRS=3&S_JSRS_ZGDB=1&csrftoken=";
            Response response = givenWithCookies()
                    .header("Content-Type", "application/x-www-form-urlencoded")
//                .params(formParams)
                    .body(data)
//               .cookies(cookies)
                    .log().all()
                    .post("ywtSldj.do?method=saveJbxx&type=0"); // 注意：可能需要有效的 CSRF Token
            List<String> cookies = response.getHeaders().getValues("Set-Cookie");
            int Code = response.getStatusCode();
            System.out.println(Code);
            String body = response.getBody().asString();
//            System.out.println(body);
            if (Code == 302) {
                for (String cookie : cookies) {
                    System.out.println("Set-Cookie Header: " + cookie);
                }
                String redirectUrl = response.getHeader("Location");
                System.out.println(redirectUrl);
                if (redirectUrl != null) {
                    Response finalResponse = givenWithCookies()
                            .when()
                        .log().all()
                            .get(redirectUrl);
                    int statusCode = finalResponse.getStatusCode();
                    System.out.println("Status Code: " + statusCode);

                    return statusCode;
                }
                return 0;
            }
        }
        return 0;
    }
    public static  List<JycInfo>  initJyclist() {
        List<JycInfo> jycInfoList = new ArrayList<>();
        Map<String, String> testData = testDataLoader.getTestData();
        String nameXzqh = testData.get("nameXzqh");
        String nameZh = testData.get("nameZh");
        String nameHy = testData.get("nameHy");
        String nameZzxs = testData.get("nameZzxs");

        String sql = "SELECT * FROM qcdz_qy_sl_qyhznr WHERE entname LIKE ?" ;

        String entname = nameZh + nameHy + "（" + nameXzqh + "）" + nameZzxs ;

        try (ResultSet rs = ConPlsqla.exec_select(sql, "%" + entname + "%")){

            while (rs != null && rs.next()) {
                JycInfo jycInfo = new JycInfo();
                jycInfo.setPripid(rs.getString("pripid"));// 替换为实际的字段名
                jycInfo.setName_id(rs.getString("name_id"));// 替换为实际的字段名
                jycInfo.setSbid(rs.getString("sbid"));
                jycInfo.setEntname(rs.getString("entname"));
                jycInfo.setProloc_location(rs.getString("proloc_location"));//详细地址
                jycInfo.setQylxdl(rs.getString("qylxdl"));//全部地址
                jycInfo.setProloc(rs.getString("proloc"));//全部地址



                // 填充更多字段
                jycInfoList.add(jycInfo);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for (JycInfo info : jycInfoList) {
            System.out.println("结果是"+info);
        }
        return jycInfoList;
    }
}